package com.ip.student.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ip.student.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ip.student.mapper.StudentInfoMapper;
import com.ip.student.models.service.IStudentInfoService;
import com.ip.student.models.bo.StudentInfoSaveBO;
import com.ip.student.models.dto.StudentInfoDTO;

/**
 * 学生基本信息控制器
 *
 * @author 张景奇
 * @Date 2025-11-03 09:19:06
 */
@DubboService
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfoDTO> implements IStudentInfoService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(StudentInfoSaveBO saveBO) {
        StudentInfoDTO dto = new StudentInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        
        // 如果前端传回的ID为null或0，则使用雪花算法生成ID
        if (saveBO.getStudentId() == null || saveBO.getStudentId() == 0) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数且在Integer范围内
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setId(id);
            dto.setStudentId(id.intValue());
        } else {
            dto.setId(saveBO.getStudentId().longValue());
            dto.setStudentId(saveBO.getStudentId());
        }
        
        // 如果nationalStudentId为空，则使用雪花算法生成编码
        if (saveBO.getNationalStudentId() == null || saveBO.getNationalStudentId().trim().isEmpty()) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setNationalStudentId("NAT-" + id);
        } else {
            dto.setNationalStudentId(saveBO.getNationalStudentId());
        }
        
        // 如果schoolStudentId为空，则使用雪花算法生成编码
        if (saveBO.getSchoolStudentId() == null || saveBO.getSchoolStudentId().trim().isEmpty()) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setSchoolStudentId("SCH-" + id);
        } else {
            dto.setSchoolStudentId(saveBO.getSchoolStudentId());
        }
        
        return this.insert(dto);
    }
}